package archer.framework.common.verifycode;

import archer.framework.common.verifycode.cache.VerifyCodeCache;
import archer.framework.utils.MapUtils;
import archer.framework.utils.RandomUtils;
import archer.framework.utils.SmartString;
import archer.framework.utils.ValidateUtils;
import archer.framework.web.sms.SMSSenderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 验证码服务
 *
 * @author christ
 * @date 2015/8/4
 */
@Component
public class VerifyCodeService {

    @Autowired
    protected VerifyCodeCache verifyCodeCache;

    @Autowired(required = false)
    protected SMSSenderService smsSenderService;

    /**
     * 发送验证码
     *
     * @param mobile
     * @throws VerifyCodeException
     */
    public void send(String mobile, String content) throws VerifyCodeException {
        send(mobile, content, 6);
    }


    /**
     * 发送验证码
     *
     * @param mobile
     * @param length
     * @throws VerifyCodeException
     */
    public void send(String mobile, String content, int length) throws VerifyCodeException {
        if (ValidateUtils.isEmpty(mobile)) {
            return;
        }

        try {
            if (smsSenderService != null) {

                // 生成随机验证码
                String verifyCode = RandomUtils.randomNumeric(length);

                // 缓存验证码
                verifyCodeCache.cacheVerifyCode(mobile, verifyCode);

                // 解析content
                if (ValidateUtils.isNotEmpty(content)) {
                    content = SmartString.template(content).bind(MapUtils.asMap("verifyCode", verifyCode)).toString();
                }

                // 调用短信发送服务发送短信
                smsSenderService.send(mobile, content);
            }

        } catch (Exception e) {
            throw new VerifyCodeException(e);
        }
    }

    /**
     * 验证码校验
     *
     * @param mobile
     * @param verifyCode
     * @return
     */
    public boolean validate(String mobile, String verifyCode) {

        if (ValidateUtils.isEmpty(mobile) || ValidateUtils.isEmpty(verifyCode)) {
            throw new IllegalArgumentException("参数错误");
        }

        boolean validate = verifyCode.equals(verifyCodeCache.getVerifyCode(mobile));

        // 验证成功后将该验证码清除掉
        if (validate) {
            verifyCodeCache.clear(mobile);
        }

        return validate;
    }

}
